package com.kmzx.one.project.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.kmzx.one.common.enums.DeletedEnum;
import com.kmzx.one.common.exceptions.NoSuchObjectException;
import com.kmzx.one.common.exceptions.ParameterNullException;
import com.kmzx.one.common.utils.MD5Util;
import com.kmzx.one.common.utils.ServletUtils;
import com.kmzx.one.common.utils.StringUtils;
import com.kmzx.one.common.utils.UUIDGenerator;
import com.kmzx.one.project.config.data.QiNiuConfig;
import com.kmzx.one.project.config.data.WXDataConfig;
import com.kmzx.one.project.entity.*;
import com.kmzx.one.project.mapper.CustomerMapper;
import com.kmzx.one.project.mapper.ProdBaseMapper;
import com.kmzx.one.project.mapper.ProdSearchMapper;
import com.kmzx.one.project.mapper.ProductMapper;
import com.kmzx.one.project.mapper.ProductSelfMapper;
import com.kmzx.one.project.mapper.RankTabMapper;
import com.kmzx.one.project.mapper.SimpleMapper;
import com.kmzx.one.project.mapper.UserCartMapper;
import com.kmzx.one.project.mapper.UserRankMapper;
import com.kmzx.one.project.mapper.WarehouseMapper;
import com.kmzx.one.project.others.common.IdAndHeader;
import com.kmzx.one.project.others.common.IdAndKinds;
import com.kmzx.one.project.others.common.IdAndTitle;
import com.kmzx.one.project.others.common.Options;
import com.kmzx.one.project.others.common.ProdAndAttr;
import com.kmzx.one.project.others.dso.ProdCatePriceDso;
import com.kmzx.one.project.others.dso.ProdJoinAWC;
import com.kmzx.one.project.others.dso.ProdJoinAttributeCategory;
import com.kmzx.one.project.others.dso.ProdJoinAttributeWithCategory;
import com.kmzx.one.project.others.dso.ProdJoinDiscount;
import com.kmzx.one.project.others.dso.ProdTransInfo;
import com.kmzx.one.project.others.dso.ProductExtraInfo;
import com.kmzx.one.project.others.dso.ProductSelfJoinSKU;
import com.kmzx.one.project.others.dso.UserRankDso;
import com.kmzx.one.project.others.dso.WarehouseStoreDso;
import com.kmzx.one.project.others.dto.*;
import com.kmzx.one.project.others.wxo.MySelfCodeUnLimit;
import com.kmzx.one.project.service.ProdService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.ansj.domain.Result;
import org.ansj.domain.Term;
import org.ansj.recognition.impl.StopRecognition;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import weixin.popular.api.TokenAPI;
import weixin.popular.api.WxaAPI;
import weixin.popular.bean.token.Token;
import weixin.popular.bean.wxa.LineColor;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ProdServiceImpl implements ProdService {


    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RedisTemplate<String, Object> objectRedisTemplate;


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private SimpleMapper simpleMapper;

    @Autowired
    private CustomerMapper customerMapper;

    // 数据配置
    @Autowired
    private QiNiuConfig qiNiuConfig;

    @Autowired
    private WXDataConfig wxConfig;

    @Autowired
    private AtomicInteger atomicInteger;

    @Autowired
    UserRankMapper userRankMapper;

    @Autowired
    private UserCartMapper userCartMapper;

    @Autowired
    ProductSelfMapper productSelfMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    private ProdSearchMapper prodSearchMapper;

    @Autowired
    private ProdBaseMapper prodBaseMapper;

    @Autowired
    private RankTabMapper rankTabMapper;


    public String getRankId(String userId) {
        List<UserRankDso> dsos = userRankMapper.selectAllRankTabs();
        String rankId = dsos.get(0).getRankId();
        if (userId != null && !userId.equals("")) {

            String s = userId.toLowerCase();
            if (!"null".equals(s)) {
                UserRankInfo info = userRankMapper.selectUserRankTabs(userId);
                if(info!=null){
                    String rankId1 = info.getRankId();
                    rankId = rankId1;
                }
            }
        }

        return rankId;
    }

    // 查找所有的产品分类
    @Override
    public List<ProdCateOutInfo> findCateAll(String userId) {
        String rankId = getRankId(userId);
        if (userId != null && !userId.equals("")) {
            List<String> specUsers = customerMapper.findSpecificUser();
            if (!CollectionUtils.isEmpty(specUsers)) {
                if (specUsers.contains(userId)) {
                    List<ProdCateOutInfo> infos = productMapper.selectCateAll();
                    return infos;
                }
            }
        }
        List<ProdCateOutInfo> infos = productMapper.selectCateByRankId(rankId);
        return infos;
    }

    @Override
    public List<ProdOutInfo> findProdByCateIdPager() throws Exception {
        String cateId = ServletUtils.getParameter("cateId");
        String userId = ServletUtils.getParameter("userId");
        String rankId = getRankId(userId);
        Integer pageNum = ServletUtils.getRequestPageNum();
        Integer pageSize = ServletUtils.getRequestPageSize();

        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;

        if (StringUtils.isEmpty(cateId)) {
            throw new ParameterNullException("cateId为空");
        }

        PageHelper.startPage(pageNum, pageSize, true);
        Page<ProdOutInfo> result = productMapper.selectProdByCateIdPager(cateId);
        List<ProdOutInfo> end = result.getResult();
        if (end == null || end.size() == 0) {
            return Collections.emptyList();
        } else {
            RankTab rankTab = rankTabMapper.selectByPrimaryKey(rankId);
            Integer rankNumber = rankTab.getRankNumber();
            List<ProdCateOutInfo> infos = productMapper.selectCateByRankId(rankId);
            if (infos != null && infos.size() > 0) {
                List<Integer> collect = infos.stream().map(lt -> lt.getCateId()).collect(Collectors.toList());
                if (!collect.contains(Integer.valueOf(cateId))) {
                    return Collections.emptyList();
                }
            }


            List<String> prodIds = end.stream().map(qq -> qq.getProdId()).collect(Collectors.toList());
            if (prodIds != null && prodIds.size() == 0) {
                return Collections.emptyList();
            }
            List<ProdCatePriceDso> priceDsos = productMapper.selectProdGroupPriceList(prodIds);


            // 所有的商品打折活动,包括所有的商品
            List<ProdJoinDiscount> discounts = productMapper.selectAllProductJoinDiscount();

            boolean specific = false;
            List<String> specUsers = customerMapper.findSpecificUser();
            if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {
                if (specUsers.contains(userId)) {
                    specific = true;
                }
            }
            if (!CollectionUtils.isEmpty(priceDsos)) {
                Map<String, List<ProdCatePriceDso>> map = priceDsos.stream().collect(Collectors.groupingBy(ProdCatePriceDso::getProductId));


                if (specific) {
                    for (ProdOutInfo prod : end) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                        if (prodCatePriceDsos != null) {
                            ProdCatePriceDso pcds = prodCatePriceDsos.get(0);
                            BigDecimal miniCost = pcds.getMiniCost();
                            miniCost = miniCost.multiply(BigDecimal.valueOf(pcds.getProdNum()));
                            prod.setProdPrice(miniCost);
                            prod.setCurrentPrice(miniCost);
                            prod.setBeauty(miniCost);
                            Integer behalf = pcds.getBehalf();
                            if (behalf != null) {
                                if (behalf == 0) {
                                    prod.setHas(true);
                                } else {
                                    prod.setHas(pcds.getNomNumbers() > 0);
                                }
                            } else {
                                prod.setHas(pcds.getNomNumbers() > 0);
                            }
                        } else {
                            prod.setProdPrice(BigDecimal.ONE);
                            prod.setCurrentPrice(BigDecimal.ONE);
                            prod.setBeauty(BigDecimal.ONE);
                        }
                    }
                } else {
                    for (ProdOutInfo prod : end) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                        if (prodCatePriceDsos != null) {
                            ProdCatePriceDso pcds = prodCatePriceDsos.get(0);
                            BigDecimal miniPrice = pcds.getMiniPrice();
                            if (pcds.getBehalf() != null) {
                                if (pcds.getBehalf() == 0) {
                                    prod.setHas(true);
                                } else {
                                    prod.setHas(pcds.getNomNumbers() > 0);
                                }
                            } else {
                                prod.setHas(pcds.getNomNumbers() > 0);
                            }
                            prod.setProdPrice(miniPrice);
                            prod.setCurrentPrice(miniPrice);
                            prod.setBeauty(miniPrice);
                        } else {
                            BigDecimal price = productMapper.selectProdGroupPrice(prod.getProdId());
                            if (price != null) {
                                prod.setProdPrice(price);
                                prod.setCurrentPrice(price);
                                prod.setBeauty(price);
                            } else {
                                prod.setProdPrice(BigDecimal.ONE);
                                prod.setCurrentPrice(BigDecimal.ONE);
                                prod.setBeauty(BigDecimal.ONE);
                            }
                        }
                    }
                    end = switchToFastProd(end, userId, discounts);
                    // 直升商品
                    for (ProdOutInfo info : end) {
                        info.setRankIcon(rankTab.getRankIcon());
                        if (rankNumber > 0 && !info.isOneValue()) {
                            if (info.getKinds() == 2) {
                                if (info.getRankNum() < rankNumber && (rankNumber > 0)) {
                                    info.setRankPrice(info.getProdPrice().multiply(rankTab.getBigRankRate()));
                                }
                            } else {
                                info.setRankPrice(info.getCurrentPrice().multiply(rankTab.getBigRankRate()));
                            }
                        }
                    }
                }
            }
            return end;
        }
    }


    public List<ProdOutInfo> switchToFastProd(List<ProdOutInfo> end, String userId, List<ProdJoinDiscount> discounts) {
        //
        List<StraightInfo> infoList = productMapper.selectAllStraightInfo();
        if (infoList == null) {
            if (!CollectionUtils.isEmpty(discounts)) {
                Map<String, List<ProdJoinDiscount>> listMap = discounts.stream().collect(Collectors.groupingBy(ProdJoinDiscount::getProductId));

                for (ProdOutInfo prod : end) {
                    String prodId = prod.getProdId();
                    List<ProdJoinDiscount> joinDiscounts = listMap.get(prodId);
                    if (joinDiscounts != null) {
                        for (ProdJoinDiscount joinDiscount : joinDiscounts) {
                            Integer discountCate = joinDiscount.getDiscountCate();
                            if (discountCate == 0) {
                                joinDiscount.setCurrentPrice(prod.getProdPrice().multiply(joinDiscount.getDiscountNum()));
                            } else if (discountCate == 1 || discountCate == 2) {
                                joinDiscount.setCurrentPrice(joinDiscount.getDiscountNum());
                            } else if (discountCate == 3) {
                                joinDiscount.setCurrentPrice(joinDiscount.getDiscountNum());
                            }
                        }
                        joinDiscounts.sort(Comparator.comparing(ProdJoinDiscount::getCurrentPrice));
                        Integer discountCate = joinDiscounts.get(0).getDiscountCate();
                        prod.setKinds(1);
                        // 0折扣  1 一口价
                        if (discountCate == 0) {
                            prod.setCurrentPrice(prod.getProdPrice().multiply(joinDiscounts.get(0).getDiscountNum()));
                        } else if (discountCate == 1) {
                            prod.setCurrentPrice(joinDiscounts.get(0).getDiscountNum());
                        } else if (discountCate == 3) {
                            prod.setOneValue(true);
                            prod.setCurrentPrice(joinDiscounts.get(0).getDiscountNum());
                        }
                        prod.setBeauty(prod.getCurrentPrice());
                        prod.setDiscountImg(joinDiscounts.get(0).getDiscountImg());

                        Integer special = joinDiscounts.get(0).getSpecial();
                        if (special != null && special == 0) {
                            if (discountCate == 2) {
                                prod.setCurrentPrice(joinDiscounts.get(0).getDiscountNum());
                                prod.setOneValue(true);
                            }
                        }
                    }
                }
            }
            return end;
        }
        if (infoList != null && infoList.size() > 0) {
            UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
            boolean had = false;
            if (userRankInfo != null) {

                List<FastProdInfo> fastProdList = new ArrayList<>();
                for (StraightInfo info : infoList) {
                    had = true;
                    String id = info.getId();
                    Page<FastProdInfo> infos = productMapper.selectFastProdInfoPaged(id);
                    fastProdList.addAll(infos.getResult());
                }
                if (had) {
                    for (ProdOutInfo prodOutInfo : end) {
                        for (FastProdInfo fastProdInfo : fastProdList) {
                            if (prodOutInfo.getProdId().equals(fastProdInfo.getProdId())) {
                                prodOutInfo.setRankNum(fastProdInfo.getRankNum());
                                prodOutInfo.setFastIcon(fastProdInfo.getFastIcon());
                                prodOutInfo.setCurrentPrice(fastProdInfo.getCurrentPrice());
                                prodOutInfo.setBeauty(fastProdInfo.getBeauty());
                                prodOutInfo.setKinds(2);
                            }
                        }
                    }
                }
            } else {
                had = true;
                List<FastProdInfo> fastProdList = new ArrayList<>();
                for (StraightInfo info : infoList) {
                    String id = info.getId();
                    Page<FastProdInfo> infos = productMapper.selectFastProdInfoPaged(id);
                    fastProdList.addAll(infos.getResult());
                }
                if (had) {
                    for (ProdOutInfo prodOutInfo : end) {
                        for (FastProdInfo fastProdInfo : fastProdList) {
                            if (prodOutInfo.getProdId().equals(fastProdInfo.getProdId())) {
                                prodOutInfo.setFastIcon(fastProdInfo.getFastIcon());
                                prodOutInfo.setCurrentPrice(fastProdInfo.getCurrentPrice());
                                prodOutInfo.setRankNum(fastProdInfo.getRankNum());
                                prodOutInfo.setBeauty(fastProdInfo.getBeauty());
                                prodOutInfo.setKinds(2);
                            }
                        }
                    }
                }
            }
            if (!CollectionUtils.isEmpty(discounts)) {
                Map<String, List<ProdJoinDiscount>> listMap = discounts.stream().collect(Collectors.groupingBy(ProdJoinDiscount::getProductId));

                for (ProdOutInfo prod : end) {
                    if (prod.getKinds() != 2) {
                        String prodId = prod.getProdId();
                        List<ProdJoinDiscount> joinDiscounts = listMap.get(prodId);
                        if (joinDiscounts != null) {
                            for (ProdJoinDiscount joinDiscount : joinDiscounts) {
                                Integer discountCate = joinDiscount.getDiscountCate();
                                if (discountCate == 0) {
                                    joinDiscount.setCurrentPrice(prod.getProdPrice().multiply(joinDiscount.getDiscountNum()));
                                } else if (discountCate == 1 || discountCate == 2) {
                                    joinDiscount.setCurrentPrice(joinDiscount.getDiscountNum());
                                } else if (discountCate == 3) {
                                    joinDiscount.setCurrentPrice(joinDiscount.getDiscountNum());
                                }
                            }
                            joinDiscounts.sort(Comparator.comparing(ProdJoinDiscount::getCurrentPrice));
                            Integer discountCate = joinDiscounts.get(0).getDiscountCate();
                            // 0折扣  1 一口价
                            if (discountCate == 0) {
                                if (joinDiscounts.get(0).getDiscountNum().compareTo(BigDecimal.ONE) != 0) {
                                    prod.setKinds(1);
                                }
                                prod.setCurrentPrice(prod.getProdPrice().multiply(joinDiscounts.get(0).getDiscountNum()));
                            } else if (discountCate == 1) {
                                prod.setKinds(1);
                                prod.setCurrentPrice(joinDiscounts.get(0).getDiscountNum());
                            } else if (discountCate == 3) {
                                prod.setKinds(1);
                                prod.setOneValue(true);
                                prod.setCurrentPrice(joinDiscounts.get(0).getDiscountNum());
                            }
                            prod.setBeauty(prod.getCurrentPrice());
                            prod.setDiscountImg(joinDiscounts.get(0).getDiscountImg());
                            Integer special = joinDiscounts.get(0).getSpecial();
                            if (special != null && special == 0) {
                                if (discountCate == 2) {
                                    prod.setCurrentPrice(joinDiscounts.get(0).getDiscountNum());
                                    prod.setOneValue(true);
                                }
                            }
                        }
                    }
                }
            }
        }
        return end;
    }


    @Override
    public ProdMainInfo findProdMainInfo2(String productId, String userId, Integer fast) throws Exception {
        String rankId = (String) ServletUtils.getAttr("level");

        List<String> specUsers = customerMapper.findSpecificUser();
        if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {

            if (specUsers.contains(userId)) {
                // 有特权,有用户,也是
                ProdMainInfo prodMainInfo = findProdMainInfo(productId, userId, rankId, true, fast);
                return prodMainInfo;
            } else { // 有特权,有用户,但不是
                ProdMainInfo prodMainInfo = findProdMainInfo(productId, userId, rankId, false, fast);
                return prodMainInfo;
            }
        } else {
            // 没特权,没用户
            // 有特权,没用户
            ProdMainInfo prodMainInfo = findProdMainInfo(productId, userId, rankId, false, fast);
            return prodMainInfo;
        }
    }

    @Override
    public ProdMainInfo findProdMainInfo(String productId, String userId) throws Exception {
//        String rankId = (String) ServletUtils.getAttr("level");
        String rankId = getRankId(userId);
        List<String> specUsers = customerMapper.findSpecificUser();
        if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {

            if (specUsers.contains(userId)) {
                // 有特权,有用户,也是
                ProdMainInfo prodMainInfo = findProdMainInfo(productId, userId, rankId, true, 0);
                return prodMainInfo;
            } else { // 有特权,有用户,但不是
                ProdMainInfo prodMainInfo = findProdMainInfo(productId, userId, rankId, false, 0);
                return prodMainInfo;
            }
        } else {
            // 没特权,没用户
            // 有特权,没用户
            ProdMainInfo prodMainInfo = findProdMainInfo(productId, userId, rankId, false, 0);
            return prodMainInfo;
        }
    }

    // 3.1 查看商品的主要信息
    public ProdMainInfo findProdMainInfo(String productId, String userId, String rankId, boolean has, Integer fast) throws Exception {

        List<String> ids = productMapper.findProdRankIds(productId);
        if (ids != null && ids.size() > 0) {
            if (!ids.contains(rankId)) {
                ProdMainInfo prodMainInfo = new ProdMainInfo();
                return prodMainInfo;
//                throw new NoSuchObjectException(204,"该商品暂时无法查看!");
            }
        }
        List<ProdJoinAttributeWithCategory> joinAttributes = productMapper.selectProdEntryInfo2(productId);
        // 所有的商品打折活动,包括所有的商品
        List<ProdJoinDiscount> discounts = productMapper.selectAllProductJoinDiscount();
        if (!CollectionUtils.isEmpty(joinAttributes)) {

            ProdJoinAttributeWithCategory joinAttribute = joinAttributes.get(0);
            ProdMainInfo result = new ProdMainInfo();
            result.setSaw(true);
            result.setEnabled(joinAttribute.getStates());
            Integer inOrOut = joinAttribute.getInOrOut();
            result.setInOrOut(inOrOut);
            result.setCurrentPrice(joinAttributes.stream().sorted(Comparator.comparing(ProdJoinAttributeWithCategory::getPrice)).findFirst().get().getPrice());
            result.setProdPrice(result.getCurrentPrice());
            if (discounts != null && discounts.size() > 0) {
                Map<String, List<ProdJoinDiscount>> listMap = discounts.stream().collect(Collectors.groupingBy(ProdJoinDiscount::getProductId));
                List<ProdJoinDiscount> discountList = listMap.get(productId);
                if (discountList != null && discountList.size() > 0) {
                    for (ProdJoinDiscount joinDiscount : discountList) {
                        Integer discountCate = joinDiscount.getDiscountCate();
                        if (discountCate == 0) {
                            joinDiscount.setCurrentPrice(result.getProdPrice().multiply(joinDiscount.getDiscountNum()));
                        } else if (discountCate == 1 || discountCate == 2) {
                            joinDiscount.setCurrentPrice(joinDiscount.getDiscountNum());
                        } else if (discountCate == 3) {
                            joinDiscount.setCurrentPrice(joinDiscount.getDiscountNum());
                        }
                    }
                    discountList.sort(Comparator.comparing(ProdJoinDiscount::getCurrentPrice));
                    ProdJoinDiscount discount = discountList.get(0);

                    // 固定折扣
                    result.setDiscountCate(discount.getDiscountCate());
                    BigDecimal currentPrice = result.getCurrentPrice();
                    if (discount.getDiscountCate() == 0) {
                        result.setDiscountImg(discount.getDiscountImg());
                        result.setDiscountNum(discount.getDiscountNum().doubleValue());
                        result.setCurrentPrice(currentPrice.multiply(discount.getDiscountNum()));
                    } else if (discount.getDiscountCate() == 1) {
                        result.setDiscountImg(discount.getDiscountImg());
                        result.setCurrentPrice(discount.getDiscountNum());
                        result.setDiscountNum(1.0);
                    } else if (discount.getDiscountCate() == 2) {
                        result.setDiscountImg(discount.getDiscountImg());
                        result.setDiscountNum(discount.getDiscountNum().doubleValue());
                        result.setCurrentPrice(discount.getDiscountNum());
                        result.setOneValue(true);
                    }
                    if (discount.getDiscountCate() == 3) {
                        result.setFast(true);
                        result.setOneValue(true);
                        result.setDiscountImg(discount.getDiscountImg());
                        result.setDiscountNum(discount.getDiscountNum().doubleValue());
                        result.setCurrentPrice(discount.getDiscountNum());
                    }
                } else {
                    result.setDiscountNum(1.0);
                }
            }


            String minPriceAs = productMapper.findProductSpecificMinPriceAs(productId);
            if (has && minPriceAs != null) {
                String[] split = minPriceAs.split("@");
                String skuId = split[0];
                String minPriceStr = split[1];
                // 特权的最小价格
                AttributeWithCategory id = productMapper.selectAttributeWithCategoryById(skuId);
                Integer prodNum = id.getProdNum();
                BigDecimal minPrice = new BigDecimal(minPriceStr).multiply(BigDecimal.valueOf(prodNum));
                result.setCurrentPrice(minPrice);
                result.setProdPrice(minPrice);
            } else {
                // 直升商品
                int prodRankNum = 0;

                List<MemberActionInfo> actionInfos = productMapper.selectProductStraight();
                if (!CollectionUtils.isEmpty(actionInfos)) {
                    List<Map<String, Object>> list = productMapper.selectProdFastKind(productId, 0);

                    if (!CollectionUtils.isEmpty(list)) {
                        for (Map<String, Object> objectMap : list) {
                            Double growthValue = (Double) objectMap.get("growthValue");
                            result.setBeauty(BigDecimal.valueOf(growthValue));
                            BigDecimal upMoney = (BigDecimal) objectMap.get("upMoney");
                            prodRankNum = (Integer) objectMap.get("rankNum");

                            result.setCurrentPrice(upMoney);
                            result.setDiscountCate(1);
                            result.setDiscountNum(upMoney.doubleValue());
                        }
                    }
                }

                if (!result.isOneValue()) {
                    UserRankInfo rankInfo = userRankMapper.selectUserRankTabs(userId);
                    if (rankInfo != null) {
                        int userRankNum = rankInfo.getRankNum();
                        if (userRankNum > 0 && (userRankNum > prodRankNum)) {
                            result.setRankPrice(result.getCurrentPrice().multiply(rankInfo.getBigRankRate()));
                            result.setRankIcon(rankInfo.getPriceIcon());
                        }

                        int isFast = productMapper.checkProdIsFast(productId);
                        if (isFast > 0) {
                            result.setFast(true);
                            if (userRankNum > 0 && (userRankNum > prodRankNum)) {
                                result.setRankPrice(result.getProdPrice().multiply(rankInfo.getBigRankRate()));
                                result.setFast(false);
                                result.setTips(true);
                                result.setRankName(rankInfo.getRankName());
                            }
                        }
                    }
                }


            }

            BigDecimal productFreight = joinAttribute.getProductFreight();
            if (productFreight == null) {
                productFreight = BigDecimal.ZERO;
            }
            BigDecimal tariffFree = joinAttribute.getTariffFree();
            if (tariffFree == null) {
                tariffFree = BigDecimal.ZERO;
            }
            result.setProdId(productId).setProdName(joinAttribute.getProductName()).setExpressFee(productFreight).setTariffFee(tariffFree);

            List<IdAndKinds> pics = productMapper.selectProdPicsByProdId(productId);

            if (!CollectionUtils.isEmpty(pics)) {
                result.setCarouselsImg(pics.stream().filter(a -> a.getKinds() == 1).map(b -> b.getId()).collect(Collectors.toList()));
                result.setDetailImg(pics.stream().filter(a -> a.getKinds() == 2).map(b -> b.getId()).collect(Collectors.toList()));

                List<String> carouselsImg = result.getCarouselsImg();
                if (carouselsImg != null && carouselsImg.size() > 0) {
                    for (int i = 0; i < carouselsImg.size(); i++) {
                        String pic = carouselsImg.get(i);
                        int dot = pic.lastIndexOf(".");
                        int subLine = pic.lastIndexOf("_");
                        String[] xes = pic.substring(subLine + 1, dot).split("×");
                        Integer width = Integer.valueOf(xes[0]);
                        Integer height = Integer.valueOf(xes[1]);
                        if (result.getMaxWidth() < width) {
                            result.setMaxWidth(width);
                        }
                        if (result.getMaxHeight() < height) {
                            result.setMaxHeight(height);
                        }
                    }
                }
            }

            Map<String, BigDecimal> freeFee = productMapper.selectProductFreeFee();
            Integer behalf = joinAttribute.getBehalf();
            if (behalf != null && behalf == 0) {
                result.setHas(true);
            } else {
//                Integer po = productMapper.selectProdAttributeStoreId3(productId);
//                if (po != null && po != 0) {
//                    result.setHas(true);
//                }

                List<WareHouseInfo> infos = productMapper.selectProdStoreAvg(productId);
                for (WareHouseInfo info : infos) {
                    int nowNumber = info.getNowNumber();
                    Integer prodNum = info.getProdNum();
                    if (prodNum != null && prodNum != 0) {
                        int changeNum = nowNumber / prodNum;
                        if (changeNum > 0) {
                            result.setHas(true);
                        } else {
                            result.setHas(false);
                        }
                    } else {
                        if (nowNumber > 0) {
                            result.setHas(true);
                        } else {
                            result.setHas(false);
                        }
                    }
                }


            }

//
            result.setFullMoney(freeFee.get("fullMoney"));
            result.setPayMoney(freeFee.get("payMoney"));

            result.setExtraRate(BigDecimal.ZERO);
            result.setExtraMoney(BigDecimal.ZERO);
            if (inOrOut == 1) {
                List<ProductExtraInfo> extraInfos = productMapper.selectProdExtraInfo("");
                if (!CollectionUtils.isEmpty(extraInfos)) {
                    ProductExtraInfo extraInfo = extraInfos.get(0);
                    result.setExtraRate(BigDecimal.valueOf(extraInfo.getChargesNumber()));
                    result.setExtraMoney(extraInfo.getChargesPrice());
                }
            }

            List<WarehouseStoreDso> store = prodBaseMapper.findProdStore(productId);
            result.setStores(Collections.emptyList());
            // 计算税费,以及货仓的来源地
            ArrayList<IdAndHeader> list = new ArrayList<>();
            if (store != null && store.size() > 0) {
                for (WarehouseStoreDso dso : store) {
                    IdAndHeader header = new IdAndHeader();
                    header.setId(dso.getStoreId())
                            .setFirst(dso.getFirst())
                            .setName(dso.getStoreName());
                    header.setTradeNum(dso.getTradeNum());
                    if (dso.getStores() > 0) {
                        if (dso.getProdNum() != null && dso.getProdNum() != 0) {
                            int i = dso.getStores() / dso.getProdNum();
                            if (i > 0) {
                                header.setHas(true);
                                header.setYou(i);
                            }
                        }
                    }
                    if (behalf != null && behalf == 0) {
                        header.setHas(true);
                        header.setYou(-1);
                    }
                    list.add(header);
                }

                if (store.size() > 1) {
                    list.sort(Comparator.comparing(IdAndHeader::getYou));
                }
            }
            result.setStores(list);
            if (inOrOut == 2) {
//                ArrayList<IdAndHeader> list = new ArrayList<>();
//                if (store != null && store.size() > 0) {
//                    for (WarehouseStoreDso dso : store) {
//                        IdAndHeader header = new IdAndHeader();
//                        header.setId(dso.getStoreId())
//                                .setFirst(dso.getFirst())
//                                .setName(dso.getStoreName());
//                        header.setTradeNum(dso.getTradeNum());
//                        if (dso.getStores() > 0) {
//                            header.setHas(true);
//                        }
//                        list.add(header);
//                    }
//                }
//                result.setStores(list);
                result.setGateFee(BigDecimal.ZERO);
                String awcId = joinAttribute.getAwcId();
                ProdSkuTaxInfo taxInfo = new ProdSkuTaxInfo(awcId, 1);
                List<ProdSkuTaxInfo> taxInfos = Arrays.asList(taxInfo);
                BigDecimal prodTax = toComputeProdTax(taxInfos, userId);
                result.setNationImg(taxInfo.getNationImg()).setNationTitle(taxInfo.getNationTitle());
                result.setGateFee(prodTax);
            }
            boolean has1 = result.isHas();
            if (joinAttribute.getStates() == 0) {
                result.setHas(has1);
            } else {
                result.setHas(false);
            }
            return result;
        }
        return null;
    }

    @Override
    public ProdSpecsInfo findProdEntryInfo(String productId, String userId, String fastId, int outInner, String tradeNum) throws Exception {

        List<ProdJoinAttributeCategory> joinAttributes = productMapper.selectProdEntryInfo(productId);
        List<ProdJoinDiscount> discounts = productMapper.selectProductJoinDiscount(productId);
        if (!CollectionUtils.isEmpty(joinAttributes)) {
            ProdJoinAttributeCategory joinAttributeCategory = joinAttributes.get(0);
            // 属性的Key
            String optionNameIds = joinAttributeCategory.getAllAttributeId();
            // 属性的Value
            String optionValueIds = joinAttributeCategory.getAllValuesId();
            String[] nameArray = optionNameIds.split(",");
            String[] idArray = optionValueIds.split(",");

            List<String> nameList = Arrays.asList(nameArray);
            List<String> idList = Arrays.asList(idArray);

            List<AttributeValues> attributeValuesList = productMapper.selectAttributeValuesByValueLists(nameList);

            List<ProductAttribute> productAttributeList = productMapper.selectProductAttributeLists(nameList);


            List<ProductAttributeValues> productAttributeValuesList = productMapper.selectProductAttributeValuesLists(idList);

            Map<String, List<AttributeValues>> nameIdListsMap = attributeValuesList.stream().collect(Collectors.groupingBy(AttributeValues::getNameId));
            HashMap<String, String> comName = new HashMap<>();
            ArrayList<ProdAndAttr> infos = new ArrayList<>();
            ArrayList<String> skuList = new ArrayList<>();
            // 直升商品
            UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
            int userRankNum = 0;
            int prodRankNum = 0;
            if (userRankInfo != null) {
                userRankNum = userRankInfo.getRankNum();
                List<MemberActionInfo> actionInfos = productMapper.selectProductStraight();
                if (!CollectionUtils.isEmpty(actionInfos)) {
                    List<Map<String, Object>> list = productMapper.selectProdFastKind(productId, userRankNum);
                    if (list != null && list.size() > 0) {
                        for (Map<String, Object> objectMap : list) {
                            String skuId = (String) objectMap.get("skuId");
                            prodRankNum = (Integer) objectMap.get("rankNum");
                            skuList.add(skuId);
                        }
                    }
                }
            }
            for (int i = 0; i < nameArray.length; i++) {

                List<AttributeValues> values = nameIdListsMap.get(nameArray[i]);
                ProdAndAttr attr = new ProdAndAttr();
                String nameId = values.get(0).getNameId();
                attr.setAttrId(nameId);

                for (ProductAttribute nameIdList : productAttributeList) {
                    if (nameId.equals(nameIdList.getId())) {
                        attr.setAttrName(nameIdList.getAttributeCategoryName());
                    }
                }
                ArrayList<IdAndTitle> idAndTitles = new ArrayList<>();
                for (ProductAttributeValues value : productAttributeValuesList) {
                    String valueId = value.getId();
                    String categoryValue = value.getCategoryValue();
                    String cateImg = value.getCateImg();
                    comName.put(valueId, categoryValue);
                    for (AttributeValues attributeValues : values) {
                        String valuesValueId = attributeValues.getValueId();
                        if (valueId.equals(valuesValueId)) {
                            IdAndTitle idAndTitle = new IdAndTitle();
                            idAndTitle.setId(valueId);
                            idAndTitle.setTitle(categoryValue);
                            idAndTitle.setIcons(cateImg);
                            if (!org.springframework.util.StringUtils.isEmpty(cateImg)) {
                                idAndTitle.setHad(1);
                            }
                            idAndTitles.add(idAndTitle);
                        }

                    }
                }
                attr.setChilds(idAndTitles);
                attr.setChildren(idAndTitles);
                infos.add(attr);
            }
            List<AttributeWithCategory> attributeWithCategories = productMapper.selectOptionIdAndValueKeys(joinAttributeCategory.getKinds());

            HashMap<String, Integer> hashMap = new HashMap<>();

            Integer inOrOut = joinAttributeCategory.getInOrOut();
            List<WareHouseInfo> houseInfos = productMapper.selectProdStore(productId);
            if (inOrOut == 2) {
                if (tradeNum != null && !"".equals(tradeNum) && !"undefined".equals(tradeNum)) {
                    houseInfos = productMapper.selectProdStoreNumLimit(productId, tradeNum);
                }
            }

            if (!CollectionUtils.isEmpty(houseInfos)) {

                for (WareHouseInfo info : houseInfos) {
                    String id = info.getAttributeWithCategoryId();
                    Integer infoNum = hashMap.get(id);
                    if (infoNum != null) {
                        hashMap.put(id, infoNum + info.getNowNumber());
                    } else {
                        hashMap.put(id, info.getNowNumber());
                    }
                }

            }
            boolean has = false;
            if (!CollectionUtils.isEmpty(discounts)) {
                has = true;
            }
            ArrayList<Options> dtos = new ArrayList<>();
//            List<FastProdInfo> result = productMapper.selectFastProdInfoPagedList2();
//            boolean flag = false;
//            if (result != null && result.size() > 0) {
//                flag = true;
//            }
            for (AttributeWithCategory key : attributeWithCategories) {
                String valuesId = key.getAllAttributeValuesId();
                String awcId = key.getId();
                Options dto = new Options();
                dto.setCombineId(valuesId);
                dto.setProdPrice(key.getPrice());
                dto.setCurrentPrice(key.getPrice());
                dto.setKinds(0);
                dto.setBottomNum(key.getMinimum());
                dto.setMax(key.getMaximum());
                dto.setTopNum(key.getMaximum());
                dto.setMaxUse(key.getMaxUse());
//                dto.setBuyNum()


//                dto.setPrice(key.getPrice());
//                dto.setOldPrice(key.getPrice());

//                dto.setDiscountCate(0);
//                dto.setDiscountNum(BigDecimal.ONE);
                if (has) {
                    BigDecimal prodPrice = dto.getProdPrice();
                    List<ProdJoinDiscount> joinDiscounts = discounts.stream().filter(ll -> ll.getSkuId().equals(awcId)).collect(Collectors.toList());
                    if (joinDiscounts != null && joinDiscounts.size() > 0) {
                        ProdJoinDiscount pjd = joinDiscounts.get(0);
                        if (pjd != null) {
                            Integer cate = joinDiscounts.get(0).getDiscountCate();
                            BigDecimal discountNum = joinDiscounts.get(0).getDiscountNum();
                            if (cate == 1) {
                                dto.setKinds(1);
                                dto.setCurrentPrice(discountNum);

                            } else if (cate == 0) {
                                if (discountNum.compareTo(BigDecimal.ONE) != 0) {
                                    dto.setCurrentPrice(prodPrice.multiply(discountNum));
                                    dto.setKinds(1);
                                }
                            } else if (cate == 2) {
                                dto.setCurrentPrice(discountNum);
                                dto.setKinds(3);
                                dto.setOneValue(true);
                            } else if (cate == 3) {
                                dto.setCurrentPrice(discountNum);
                                dto.setKinds(3);
                                dto.setOneValue(true);
                                dto.setTeBie(2);
                            }
                        }
                    }
                }
                dto.setBeauty(dto.getCurrentPrice());
                String[] ls = valuesId.split(",");
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < ls.length; i++) {
                    builder.append(comName.get(ls[i]) + ",");
                }
                dto.setCombineName(builder.substring(0, builder.length() - 1));
                List<String> op = Arrays.asList(ls);
                dto.setIdArray(op);
                dto.setId(awcId);
                Integer behalf = joinAttributeCategory.getBehalf();
                Integer prodNum = key.getProdNum();
                if (behalf != null && behalf == 0) {
                    Integer hasNumber = productMapper.selectProdAttributeStoreId2(awcId);
                    if (hasNumber != null) {
                        dto.setHas(true);
                        dto.setNumber(100);
                    }
                } else {
                    Integer infoNum = hashMap.get(awcId);
                    if (infoNum != null) {
                        if (prodNum != null && prodNum != 0) {
                            int changeHas = infoNum / prodNum;
                            if (changeHas > 0) {
                                dto.setHas(true);
                                dto.setNumber(infoNum / prodNum);
                            } else {
                                dto.setHas(false);
                            }
                        } else {
                            dto.setHas(true);
                            dto.setNumber(infoNum);
                        }
                    } else {
                        dto.setHas(false);
                    }

                }
                if (skuList != null && skuList.size() > 0) {
                    boolean contains = skuList.contains(awcId);
                    dto.setCar(!contains);
                    dto.setFast(contains);
                    if (contains) {
                        BigDecimal upPrice = productMapper.selectFastProdBySku(awcId);
                        if (upPrice != null && upPrice.compareTo(BigDecimal.ZERO) > 0) {
                            dto.setCurrentPrice(upPrice);
                            dto.setKinds(2);
                            dto.setFast(true);
                            dto.setBeauty(upPrice);
                        }
                    }
                }
                // 临时补充用
                if (dto.getTeBie() == 2) {
                    dto.setFast(true);
                    dto.setLatest(true);
                }
                if (!dto.isOneValue()) {
                    // 直升商品
                    if (dto.getKinds() == 2) {
                        // 对用户不满足,正常价走
                        if (userRankNum > 0) {
                            if (userRankNum > prodRankNum) {
                                dto.setCurrentPrice(dto.getProdPrice());
                                dto.setRankIcon(userRankInfo.getPriceIcon());
                                dto.setRankPrice(dto.getProdPrice().multiply(userRankInfo.getBigRankRate()));
                            }
                        }
                    } else {
                        //  不是直升
                        if (userRankNum > 0) {
                            dto.setRankIcon(userRankInfo.getPriceIcon());
                            dto.setRankPrice(dto.getCurrentPrice().multiply(userRankInfo.getBigRankRate()));
//                        dto.setCurrentPrice(dto.getProdPrice());
                        }
                    }
                }
                if (houseInfos != null && houseInfos.size() > 0) {
                    int maxLimit = houseInfos.get(0).getMaxLimit();
//                    int nowNumber = houseInfos.get(0).getNowNumber();
//                    int max = dto.getMax();
//                    if(nowNumber<=max){
//                        maxLimit = nowNumber;
//                    } else {
//                        maxLimit = max;
//                    }
                    dto.setMax(maxLimit);
                    if (joinAttributeCategory.getContainsPack() == 0) {
                        List<ProductSelfJoinSKU> joinSKUS = productSelfMapper.selectProductSelfJoinSKU(productId);
                        if (joinSKUS != null && joinSKUS.size() > 0) {
                            int sum = joinSKUS.stream().mapToInt(sl -> sl.getNeedNum() * sl.getProdNum()).sum();
                            dto.setInnerTypes(joinSKUS.size());
                            dto.setInnerProds(sum);
                        }

                        dto.setBuyNum(maxLimit / dto.getInnerProds());

                    } else {
                        dto.setInnerProds(prodNum);
//                        dto.setBuyNum(maxLimit / dto.getInnerProds());
//                        dto.setBuyNum(maxLimit);
                        if (inOrOut == 2) {
                            dto.setBuyNum(maxLimit / dto.getInnerProds());
                            dto.setMax(maxLimit);

                            if (dto.getNumber()<dto.getBuyNum()) {
                                dto.setBuyNum(dto.getNumber());
                                if(dto.getBottomNum()>dto.getBuyNum()){
                                    dto.setHas(false);
                                }
                            }
                        } else {

                            int maxUse = dto.getMaxUse();
                            if (maxUse == 1) {
                                dto.setMax(0);
                            } else {
                                if (dto.getNumber() >= dto.getTopNum()) {
                                    dto.setBuyNum(dto.getTopNum());
                                    dto.setMax(dto.getTopNum());
                                } else {
                                    dto.setMax(dto.getNumber());
                                    dto.setBuyNum(dto.getNumber());
                                }

                                if (dto.getNumber()<dto.getBuyNum()) {
                                    dto.setBuyNum(dto.getNumber());
                                    if(dto.getBottomNum()>dto.getBuyNum()){
                                        dto.setHas(false);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    int maxUse = dto.getMaxUse();
                    if (maxUse == 1) {
                        dto.setMax(0);
                    } else {
                        if (dto.getNumber() >= dto.getTopNum()) {
                            dto.setBuyNum(dto.getTopNum());
                            dto.setMax(dto.getTopNum());
                        } else {
                            dto.setMax(dto.getNumber());
                            dto.setBuyNum(dto.getNumber());
                        }
                    }
                }
                dtos.add(dto);
            }
            ProdSpecsInfo details = new ProdSpecsInfo();
            details.setProductName(joinAttributes.get(0).getProductName());
            details.setProdName(joinAttributes.get(0).getProductName());
            details.setProdId(productId);
            details.setOptionsCount(nameArray.length);
            details.setInfos(infos);
//          details.setKvs(hashMap);
            details.setKvMoney(dtos);
            List<String> specUsers = customerMapper.findSpecificUser();

            if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "") && (specUsers.contains(userId) && !CollectionUtils.isEmpty(houseInfos))) {
                for (Options dto : dtos) {
                    String id = dto.getId();
                    List<WareHouseInfo> in = houseInfos.stream().filter(lg -> lg.getAttributeWithCategoryId().equals(id)).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(in)) {
                        String skuId = in.get(0).getAttributeWithCategoryId();
                        AttributeWithCategory sku = productMapper.selectAttributeWithCategoryById(skuId);
                        Integer prodNum = sku.getProdNum();
                        dto.setCurrentPrice(in.get(0).getEnterCost().multiply(BigDecimal.valueOf(prodNum)));
                        dto.setRankPrice(null);
                        dto.setProdPrice(in.get(0).getEnterCost().multiply(BigDecimal.valueOf(prodNum)));
//                        dto.setCurrentPrice(in.get(0).getEnterCost());
                    }
                }
            }
            return details;
        }
        return null;
    }

    @Override
    public String doShareGoods(String userId, String productId, String fast) throws Exception {

        if (userId == null || (userId != null && userId == "")) {
            throw new NoSuchObjectException("该用户信息不存在");
        }
        if (fast == null || "".equals(fast)) {
            fast = "false";
        }
        List<UserSharePics> userSharePics = simpleMapper.selectUserSharePics(userId, productId, fast);

        if (!CollectionUtils.isEmpty(userSharePics)) {
            UserSharePics pics = userSharePics.get(0);
            return pics.getShareImg();
        }


        String scene = MD5Util.MD5Encode(productId + "/" + userId + "/" + fast, null);
        MySelfCodeUnLimit getwxacodeunlimit = new MySelfCodeUnLimit();

        getwxacodeunlimit.setAuto_color(true);
        getwxacodeunlimit.setScene(scene);
        getwxacodeunlimit.setWidth(430);
        getwxacodeunlimit.setPage("pages/gift_details/gift_details");
        LineColor lineColor = new LineColor();
        lineColor.setR("");
        lineColor.setG("");
        lineColor.setB("");
        getwxacodeunlimit.setIs_hyaline(true);
        getwxacodeunlimit.setLine_color(lineColor);

        BufferedImage bufferedImage = WxaAPI.getwxacodeunlimit(getRightAccessToken(), getwxacodeunlimit);
        logger.info("微信返回小程序码OK");
        String sendImg;

        logger.info("微信返回的小程序码:{}" + bufferedImage.toString());


        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
        ImageIO.write(bufferedImage, "png", imageOutput);
        InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        String png = generateFileName("png");
        String fullPath = "kmzx/share/" + png;
        asyncUpload(fullPath, byteArrayInputStream);
        String sendPath = qiNiuConfig.getDomainHost() + fullPath;

        sendImg = sendPath;
        logger.info("生成小程序码图片完成,地址:{}", sendImg);
        UserSharePics qrCode = new UserSharePics();
        qrCode.setId(UUIDGenerator.generate())
                .setUserId(userId)
                .setProductId(productId)
                .setCreateTime(new Date())
                .setShareImg(sendImg)
                .setRemarks(fast)
                .setOptions(getwxacodeunlimit.getScene())
                .setStates(0);
        simpleMapper.insertUserSharePics(qrCode);
        return sendImg;
    }

    @Override
    public Map<String, String> doSceneToProduct(String scene) throws Exception {

        Map<String, String> product = simpleMapper.selectSceneByProdId(scene);
        if (!CollectionUtils.isEmpty(product)) {
            return product;
        }
        return null;
    }


    public String generateFileName(String fileType) {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        StringBuilder sb = new StringBuilder();
        sb.append(year);
        sb.append("/");
        sb.append(calendar.get(Calendar.MONTH) + 1);
        sb.append("/");
        sb.append(calendar.get(Calendar.DAY_OF_MONTH));
        sb.append("-");
        sb.append(calendar.get(Calendar.HOUR_OF_DAY));// 1位
        sb.append(calendar.get(Calendar.MINUTE));// 1位
        sb.append(calendar.get(Calendar.SECOND));// 1位
        sb.append("-");
        sb.append(atomicInteger.getAndIncrement());
        sb.append(RandomStringUtils.randomAlphanumeric(6));
        sb.append(".");
        sb.append(fileType);
        return sb.toString();
    }


    /**
     * 异步上传数据
     *
     * @param fileName
     * @param input
     */
    public void asyncUpload(String fileName, InputStream input) {
        Configuration cfg = new Configuration(Zone.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = qiNiuConfig.getAppKey();
        String secretKey = qiNiuConfig.getAppSecret();
        String bucket = qiNiuConfig.getBucketName1();
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(input, fileName, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            logger.info("请求返回的数据key:{}", putRet.key);
            logger.info("请求返回的数据Hash:{}", putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
            }
        }
    }

    public String getRightAccessToken() {
        Object obj = stringRedisTemplate.opsForValue().get("messageToken");
        String wxTokens = null;
        if (obj != null) {
            String mt = (String) obj;
            wxTokens = mt;
        } else {
            Token token = TokenAPI.token(wxConfig.getAppId(), wxConfig.getAppSecret());
            String access_token = token.getAccess_token();
            int second = token.getExpires_in();
            wxTokens = access_token;
            stringRedisTemplate.opsForValue().set("messageToken", access_token, second, TimeUnit.SECONDS);
        }
        return wxTokens;
    }


    @Override
    public FastZoneInfo findStraightListProduct(String fastId, String userId, Integer pageNum, Integer pageSize) {
        if (userId == null || userId == "") {
            StraightInfo fastInfo = productMapper.selectStraightInfoById(fastId);
            if (fastInfo == null) {
                throw new ParameterNullException("直升物品暂无!");
            }
            FastZoneInfo zoneInfo = new FastZoneInfo();
            zoneInfo.setFastId(fastId).setRankId("").setRankNum(0);
            zoneInfo.setHeaderImg(fastInfo.getStraightImg4());


            PageHelper.startPage(pageNum, pageSize, true);
            Page<FastProdInfo> paged = productMapper.selectFastProdInfoPaged(fastId);
            List<FastProdInfo> result = paged.getResult();
            if (result != null && result.size() > 0) {
                List<String> prodIds = result.stream().map(qq -> qq.getProdId()).collect(Collectors.toList());
                List<ProdCatePriceDso> priceDsos = productMapper.selectProdGroupPriceList(prodIds);
                if (!CollectionUtils.isEmpty(priceDsos)) {
                    Map<String, List<ProdCatePriceDso>> map = priceDsos.stream().collect(Collectors.groupingBy(ProdCatePriceDso::getProductId));
                    for (FastProdInfo prodInfo : result) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prodInfo.getProdId());
                        prodInfo.setKinds(2);
                        prodInfo.setHas(prodCatePriceDsos.get(0).getNomNumbers() > 0);
                    }
                }
            }
            zoneInfo.setChildren(result);
            return zoneInfo;
        } else {
            if (checkSuper(userId)) {
                return null;
            }
            UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
            int rankNum = userRankInfo.getRankNo();
            StraightInfo fastInfo = productMapper.selectStraightInfoById(fastId);
            if (fastInfo == null) {
                throw new ParameterNullException("直升物品暂无!");
            }

            FastZoneInfo zoneInfo = new FastZoneInfo();
            zoneInfo.setFastId(fastId).setRankId(userRankInfo.getRankId()).setRankNum(rankNum);
            zoneInfo.setHeaderImg(fastInfo.getStraightImg4());


            PageHelper.startPage(pageNum, pageSize, true);
            Page<FastProdInfo> paged = productMapper.selectFastProdInfoPaged(fastId);
            List<FastProdInfo> result = paged.getResult();
            if (result != null && result.size() > 0) {
                List<String> prodIds = result.stream().map(qq -> qq.getProdId()).collect(Collectors.toList());
                List<ProdCatePriceDso> priceDsos = productMapper.selectProdGroupPriceList(prodIds);
                if (!CollectionUtils.isEmpty(priceDsos)) {
                    Map<String, List<ProdCatePriceDso>> map = priceDsos.stream().collect(Collectors.groupingBy(ProdCatePriceDso::getProductId));
                    for (FastProdInfo prodInfo : result) {
                        prodInfo.setKinds(2);
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prodInfo.getProdId());
                        if (prodCatePriceDsos != null && prodCatePriceDsos.size() > 0) {
                            prodInfo.setHas(prodCatePriceDsos.get(0).getNomNumbers() > 0);
                        } else {
                            prodInfo.setHas(false);
                        }
                    }
                }
            }
            // 直升商品
            if (rankNum > 0) {
                for (FastProdInfo info : result) {
                    BigDecimal currentPrice = info.getProdPrice();
                    if (rankNum > info.getRankNum()) {
                        info.setRankIcon(userRankInfo.getPriceIcon());
                        info.setRankPrice(currentPrice.multiply(userRankInfo.getBigRankRate()));
                    }
                }
            }
            zoneInfo.setChildren(result);
            return zoneInfo;
        }
    }

    @Override
    public FastProdMainInfo selectFastProdMainInfo(String prodId, String skuId, String userId) {
        if (checkSuper(userId)) {
            return null;
        }
        List<ProdJoinAttributeWithCategory> joinAttributes = productMapper.selectProdEntryInfo2(prodId);
        if (!CollectionUtils.isEmpty(joinAttributes)) {
            ProdJoinAttributeWithCategory joinAttribute = joinAttributes.get(0);
            FastProdMainInfo result = new FastProdMainInfo();
            result.setEnabled(joinAttribute.getStates());
            Integer inOrOut = joinAttribute.getInOrOut();
            result.setInOrOut(inOrOut);
            result.setKinds(2);
            result.setProdPrice(joinAttribute.getPrice());
            result.setCurrentPrice(result.getProdPrice());

            BigDecimal productFreight = joinAttribute.getProductFreight();
            if (productFreight == null) {
                productFreight = BigDecimal.ZERO;
            }
            BigDecimal tariffFree = joinAttribute.getTariffFree();
            if (tariffFree == null) {
                tariffFree = BigDecimal.ZERO;
            }
            result.setProdId(prodId).setProdName(joinAttribute.getProductName()).setExpressFee(productFreight).setTariffFee(tariffFree);

            List<IdAndKinds> pics = productMapper.selectProdPicsByProdId(prodId);

            if (!CollectionUtils.isEmpty(pics)) {
                result.setCarouselsImg(pics.stream().filter(a -> a.getKinds() == 1).map(b -> b.getId()).collect(Collectors.toList()));
                result.setDetailImg(pics.stream().filter(a -> a.getKinds() == 2).map(b -> b.getId()).collect(Collectors.toList()));
            }

            Map<String, BigDecimal> freeFee = productMapper.selectProductFreeFee();
            Integer po = productMapper.selectProdAttributeStoreId3(prodId);
            if (po != null && po != 0) {
                result.setHas(true);
            }
            result.setFullMoney(freeFee.get("fullMoney"));
            result.setPayMoney(freeFee.get("payMoney"));


            result.setExGateFullMoney(freeFee.get("fullMoney"));
            result.setExGateAppendMoney(freeFee.get("payMoney"));

//            result.setExtraRate(BigDecimal.ZERO);
//            result.setExtraMoney(BigDecimal.ZERO);
            if (inOrOut == 1) {
                List<ProductExtraInfo> extraInfos = productMapper.selectProdExtraInfo("");
                if (!CollectionUtils.isEmpty(extraInfos)) {
                    ProductExtraInfo extraInfo = extraInfos.get(0);
//                    result.setExtraRate(BigDecimal.valueOf(extraInfo.getChargesNumber()));
//                    result.setExtraMoney(extraInfo.getChargesPrice());
                    int toUse = extraInfo.getToUse();
                    int toUse2 = extraInfo.getToUse2();
                    if (toUse == 1) {
                        result.setExFee(extraInfo.getChargesPrice());
                    }
                    if (toUse2 == 1) {
                        result.setGateFeeRate(BigDecimal.valueOf(extraInfo.getChargesNumber()));
                    }
                }
            }
            return result;
        }
        return null;
    }


    //  // 精选品牌

    @Override
    public FastZoneOutInfo findFastZone(String userId) {
        FastZoneOutInfo outInfo = new FastZoneOutInfo();
        outInfo.setUserId(userId).setFlag(0).setRankNum(0);
        List<MemberActionInfo> actionInfos = productMapper.selectProductStraight();
        if (userId == null || userId == "") {
            if (actionInfos != null && actionInfos.size() > 0) {
                outInfo.setFlag(1);
                outInfo.setVipImg(actionInfos.get(0).getPicOne());
                outInfo.setVipUrl(actionInfos.get(0).getFastId());
                if (actionInfos.size() == 2) {
                    outInfo.setSvipImg(actionInfos.get(1).getPicOne());
                    outInfo.setSvipUrl(actionInfos.get(1).getFastId());
                    outInfo.setFlag(3);
                }
            }
            return outInfo;
        } else {
            UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
            if (userRankInfo == null) {
                if (actionInfos != null && actionInfos.size() > 0) {
                    outInfo.setFlag(1);
                    outInfo.setRankNum(0);
                    outInfo.setVipImg(actionInfos.get(0).getPicOne());
                    outInfo.setVipUrl(actionInfos.get(0).getFastId());
                    if (actionInfos.size() == 2) {
                        outInfo.setSvipImg(actionInfos.get(1).getPicOne());
                        outInfo.setSvipUrl(actionInfos.get(1).getFastId());
                        outInfo.setFlag(3);
                    }
                }
                return outInfo;
            } else {
                int rankNum = userRankInfo.getRankNo();
                outInfo.setRankNum(rankNum);
                if (actionInfos.size() == 1) {
                    outInfo.setFlag(1);
                    outInfo.setVipImg(actionInfos.get(0).getPicOne());
                    outInfo.setVipUrl(actionInfos.get(0).getFastId());
                } else if (actionInfos.size() == 2) {
                    outInfo.setFlag(1);
                    outInfo.setVipImg(actionInfos.get(0).getPicOne());
                    outInfo.setVipUrl(actionInfos.get(0).getFastId());
                    outInfo.setSvipImg(actionInfos.get(1).getPicOne());
                    outInfo.setSvipUrl(actionInfos.get(1).getFastId());
                    outInfo.setFlag(3);
                }
            }
        }
        return outInfo;
    }

    // todo need redo temp
    @Override
    public List<TempActiveInfo> findTempActiveInfo(String userId) {


//        StraightInfo fastInfo = productMapper.selectStraightInfoById2(1);
//        if (fastInfo == null) {
//            throw new ParameterNullException("直升物品暂无!");
//        }
//
//        IdAndTitle title = productMapper.selectTempOSS();
//
//
////        PageHelper.startPage(pageNum, pageSize, true);
//        Page<FastProdInfo> paged = productMapper.selectFastProdInfoPaged(fastInfo.getId());
//        List<FastProdInfo> result = paged.getResult();
//
//        if (result != null && result.size() > 0) {
//            List<TempActiveInfo> infos = new ArrayList<>();
//            for (int i = 0; i < result.size(); i++) {
//                TempActiveInfo info = new TempActiveInfo();
//                info.setProdId(result.get(i).getProdId());
//                if (i == 0) {
//                    if (title != null) {
//                        info.setSvipImg(title.getId());
//                    }
//                } else if (i == 1) {
//                    if (title != null) {
//                        info.setSvipImg(title.getTitle());
//                    }
//                }
//                infos.add(info);
//            }
//            return infos;
//        }

        List<TempActiveInfo> titles = productMapper.selectTempActivity();
        if (titles != null && titles.size() > 0) {
            for (TempActiveInfo title : titles) {
                title.setKinds(1);
                int i = productMapper.checkIsFastProd(title.getProdId());
                if (i > 0) {
                    title.setKinds(2);
                }
            }
            return titles;
        } else {
            ArrayList<TempActiveInfo> list = new ArrayList<>();
            return list;
        }
    }

    @Override
    public BigDecimal toComputeProdTax(List<ProdSkuTaxInfo> skuIds, String userId) {
        // 额外费
        List<ProductExtraInfo> extraFees = userCartMapper.selectProdExtraInfo();
        if (extraFees != null && extraFees.size() > 0) {
            List<String> specificUser = customerMapper.findSpecificUser();
            boolean isGod = false;
            if (specificUser != null && specificUser.size() > 0) {
                if (specificUser.contains(userId)) {
                    isGod = true;
                }
            }
            int rankNum = 0;
            UserRankInfo rankInfo = userRankMapper.selectUserRankTabs(userId);
            if (rankInfo != null) {
                rankNum = rankInfo.getRankNum();
            }
            ProductExtraInfo otherFee = extraFees.get(0);
            // todo  关税
//            double chargesNumber = otherFee.getChargesNumber();
            // todo  关税
            BigDecimal chargesNumber = BigDecimal.valueOf(otherFee.getChargesNumber());
            BigDecimal tempRateMoney = BigDecimal.ZERO;
            tempRateMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
            for (ProdSkuTaxInfo skuInfo : skuIds) {
                ProdJoinAWC joinAWC = userCartMapper.selectProdCartInfos(skuInfo.getSkuId());


                if (joinAWC == null) {
                    throw new ParameterNullException("您购买的物品部分已下架,下单失败!");
                }
                Integer acStates = joinAWC.getAcStates();
                if (acStates == 1) {
                    throw new ParameterNullException("商品[ " + joinAWC.getProdName() + " ]已下架");
                }
                Integer prodStates = joinAWC.getProdStates();
                if (prodStates == 1) {
                    throw new ParameterNullException("商品[ " + joinAWC.getProdName() + " ]已下架");
                }
                Integer inOrOut = joinAWC.getInOrOut();

                if (inOrOut == 0 || inOrOut == 1) {
                    return BigDecimal.ZERO;
                }
                List<ProductExtraInfo> collect = extraFees.stream().filter(ll -> ll.getTradeType() == inOrOut).collect(Collectors.toList());

                if (collect != null && collect.size() > 0) {
                    double number = collect.get(0).getChargesNumber();
                    chargesNumber = BigDecimal.valueOf(number);
                }
                Integer isSuit = joinAWC.getIsSuit();
                if (isGod) {
                    if (isSuit != null && isSuit == 0) {
                        List<ProductSelf> selfList = productSelfMapper.selectByProdIdHas2(joinAWC.getProdId(), 1);
                        for (ProductSelf productSelf : selfList) {
                            List<ProdJoinAttributeWithCategory> prodJoinAttributeWithCategories = productMapper.selectProdEntryInfo2(productSelf.getProductSubsId());
                            ProdJoinAttributeWithCategory prodJoinAttributeWithCategory = prodJoinAttributeWithCategories.get(0);

                            Integer isMulti = productSelf.getIsMulti();
                            if (isMulti == 0) {
                                // 多属性的物品
                                List<ProdJoinAttributeWithCategory> pjawc = productMapper.selectProdSKUEntryInfo(productSelf.getSkuId());
                                prodJoinAttributeWithCategory = pjawc.get(0);
                            }

                            List<Warehouse> swh = warehouseMapper.selectWarehouseInfoAll(prodJoinAttributeWithCategory.getAwcId());
                            BigDecimal nowCost = swh.get(swh.size() - 1).getNowCost();
                            BigDecimal decimal = nowCost.multiply(BigDecimal.valueOf(prodJoinAttributeWithCategory.getProdNum()))
                                    .multiply(chargesNumber).multiply(BigDecimal.valueOf(skuInfo.getNum()));
                            tempRateMoney = tempRateMoney.add(decimal);
                        }
                    } else {
                        List<Warehouse> swh = warehouseMapper.selectWarehouseInfoAll(skuInfo.getSkuId());
                        BigDecimal nowCost = swh.get(swh.size() - 1).getNowCost();
                        BigDecimal decimal = nowCost.multiply(BigDecimal.valueOf(joinAWC.getSelfNum()))
                                .multiply(chargesNumber).multiply(BigDecimal.valueOf(skuInfo.getNum()));
                        tempRateMoney = tempRateMoney.add(decimal).setScale(2, RoundingMode.HALF_UP);
                    }
                } else {
                    ProdJoinDiscount prodJoinDiscount = userCartMapper.selectProductSkuOneJoinDiscount(skuInfo.getSkuId());

                    // todo 商品的打折种类,
                    // todo  1,固定金额
                    // todo  0,折扣率
                    BigDecimal oldPrice = joinAWC.getProdPrice();
                    BigDecimal prodPrice = joinAWC.getProdPrice();
                    if (prodJoinDiscount != null) {
                        BigDecimal discountNum = prodJoinDiscount.getDiscountNum();
                        Integer discountCate = prodJoinDiscount.getDiscountCate();
                        if (discountNum != null) {
                            if (discountCate == 1 || discountCate == 2) {
                                prodPrice = discountNum;
                            } else if (discountCate == 0) {
                                prodPrice = prodPrice.multiply(discountNum);
                            } else if (discountCate == 2) {
                                prodPrice = discountNum;
                            } else if (discountCate == 3) {
                                prodPrice = discountNum;
                            }


                        }


                    }

                    List<FastProdInfo> prodInfos = productMapper.selectFastProdInfoPagedList2();
                    if (prodInfos != null && prodInfos.size() > 0) {
                        Stream<FastProdInfo> fastProdInfoStream = prodInfos.stream().filter(fp -> fp.getProdId().equals(joinAWC.getProdId()) && fp.getSkuId().equals(skuInfo.getSkuId()));
                        if (fastProdInfoStream.count() > 0) {

                            FastProdInfo fastProdInfo = prodInfos.stream().filter(fp -> fp.getProdId().equals(joinAWC.getProdId()) && fp.getSkuId().equals(skuInfo.getSkuId())).findAny().get();
                            if (rankNum <= fastProdInfo.getRankNum()) {
                                prodPrice = fastProdInfo.getCurrentPrice();
                            }
                        }
                    }

                    if (isSuit != null && isSuit == 0) {
                        List<ProductSelf> selfList = productSelfMapper.selectByProdIdHas2(joinAWC.getProdId(), 1);

                        int tempOne = -1;
                        BigDecimal saleRealMoney = BigDecimal.ZERO;
                        for (int i = 0; i < selfList.size(); i++) {
                            ProductSelf productSelf = selfList.get(i);
                            List<ProdJoinAttributeWithCategory> prodJoinAttributeWithCategories = productMapper.selectProdEntryInfo2(productSelf.getProductSubsId());
                            ProdJoinAttributeWithCategory pjawc = prodJoinAttributeWithCategories.get(0);

                            Integer isMulti = productSelf.getIsMulti();
                            if (isMulti == 0) {
                                // 多属性的物品
                                pjawc = productMapper.selectProdSKUEntryInfo(productSelf.getSkuId()).get(0);
                            }

                            ProdSkuTaxReq taxReq = productMapper.selectProdTaxExtra(productSelf.getProductSubsId());
                            skuInfo.setNationImg(taxReq.getNationImg()).setNationTitle(taxReq.getNationTitle());
                            Integer prodNum = pjawc.getProdNum();
                            productSelf.setTaxReq(taxReq);
                            productSelf.setProfiles(pjawc.getProfiles());
                            productSelf.setProdNum(BigDecimal.valueOf(prodNum));
                            BigDecimal price = pjawc.getPrice();
                            if (prodNum == 1) {
                                tempOne = i;
                            }
                            BigDecimal d2 = price.multiply(BigDecimal.valueOf(prodNum)).multiply(prodPrice);
                            BigDecimal currentPrice = d2.divide(oldPrice, 1, BigDecimal.ROUND_HALF_UP);
                            productSelf.setCurrentPrice(currentPrice.divide(BigDecimal.valueOf(prodNum), 1, BigDecimal.ROUND_HALF_UP));
                            saleRealMoney = saleRealMoney.add(productSelf.getCurrentPrice().multiply(BigDecimal.valueOf(productSelf.getNeedNum())));
                        }
                        if (saleRealMoney.compareTo(prodPrice) != 0) {
                            if (saleRealMoney.compareTo(prodPrice) > 0) {
                                BigDecimal tooMoney = saleRealMoney.subtract(prodPrice);
                                if (tempOne != -1) {
                                    BigDecimal currentPrice = selfList.get(tempOne).getCurrentPrice();
                                    selfList.get(tempOne).setCurrentPrice(currentPrice.subtract(tooMoney));
                                }
                            } else {
                                BigDecimal lessMoney = prodPrice.subtract(saleRealMoney);
                                if (tempOne != -1) {
                                    BigDecimal currentPrice = selfList.get(tempOne).getCurrentPrice();
                                    selfList.get(tempOne).setCurrentPrice(currentPrice.add(lessMoney));
                                }
                            }
                        }


                        for (ProductSelf productSelf : selfList) {
                            ProdSkuTaxReq taxReq = productSelf.getTaxReq();
                            BigDecimal price = productSelf.getCurrentPrice();
                            if (taxReq != null) {
                                BigDecimal prodCurrentPriceUnit = price.divide(productSelf.getProdNum(), 2, RoundingMode.HALF_UP);
                                BigDecimal tempMoney = taxReq.getCriticalValue();
                                String prodSpecSim = taxReq.getProdSpecSim();
                                BigDecimal decimal = BigDecimal.ONE;
                                try {
                                    if (prodSpecSim != null && !"".equals(prodSpecSim)) {
                                        decimal = new BigDecimal(taxReq.getProdSpecSim());
                                    } else {
                                        String s = productMapper.selectProdSpedUnit(productSelf.getProfiles());
                                        if (s != null && !"".equals(s)) {
                                            decimal = new BigDecimal(s);
                                        } else {
                                            decimal = BigDecimal.ONE;
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    String s = productMapper.selectProdSpedUnit(productSelf.getProfiles());
                                    if (s != null && !"".equals(s)) {
                                        decimal = new BigDecimal(s);
                                    } else {
                                        decimal = BigDecimal.ONE;
                                    }
                                }

                                prodCurrentPriceUnit = prodCurrentPriceUnit.divide(decimal, 2, BigDecimal.ROUND_HALF_UP);
                                if (tempMoney.compareTo(prodCurrentPriceUnit) <= 0) {
                                    BigDecimal subRateMoney = price.multiply(BigDecimal.valueOf(productSelf.getNeedNum())).multiply(taxReq.getLargeTax());
                                    subRateMoney = subRateMoney.multiply(BigDecimal.valueOf(skuInfo.getNum()));
                                    subRateMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    tempRateMoney = tempRateMoney.add(subRateMoney).setScale(2, BigDecimal.ROUND_HALF_UP);
                                } else {
                                    BigDecimal subRateMoney = price.multiply(BigDecimal.valueOf(productSelf.getNeedNum())).multiply(chargesNumber);
                                    subRateMoney = subRateMoney.multiply(BigDecimal.valueOf(skuInfo.getNum()));
                                    subRateMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    tempRateMoney = tempRateMoney.add(subRateMoney).setScale(2, BigDecimal.ROUND_HALF_UP);
                                }
                            } else {
                                BigDecimal multiply = price.multiply(BigDecimal.valueOf(productSelf.getNeedNum())).multiply(chargesNumber);
                                multiply = multiply.multiply(BigDecimal.valueOf(skuInfo.getNum()));
                                multiply.setScale(2, BigDecimal.ROUND_HALF_UP);
                                tempRateMoney = tempRateMoney.add(multiply).setScale(2, BigDecimal.ROUND_HALF_UP);
                            }
                        }
                    } else {

                        ProdSkuTaxReq taxReq = productMapper.selectProdTaxExtra(joinAWC.getProdId());
                        if (taxReq != null) {
                            skuInfo.setNationImg(taxReq.getNationImg()).setNationTitle(taxReq.getNationTitle());
                            BigDecimal prodCurrentPriceUnit = prodPrice.divide(BigDecimal.valueOf(joinAWC.getSelfNum()), 2, RoundingMode.HALF_UP);
                            BigDecimal tempMoney = taxReq.getCriticalValue();
                            String prodSpecSim = taxReq.getProdSpecSim();
                            BigDecimal decimal = BigDecimal.ONE;
                            try {
                                if (prodSpecSim != null && !"".equals(prodSpecSim)) {
                                    decimal = new BigDecimal(taxReq.getProdSpecSim());
                                } else {
                                    String s = productMapper.selectProdSpedUnit(joinAWC.getProdProfiles());
                                    if (s != null && !"".equals(s)) {
                                        decimal = new BigDecimal(s);
                                    } else {
                                        decimal = BigDecimal.ONE;
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                String s = productMapper.selectProdSpedUnit(joinAWC.getProdProfiles());
                                if (s != null && !"".equals(s)) {
                                    decimal = new BigDecimal(s);
                                } else {
                                    decimal = BigDecimal.ONE;
                                }
                            }
                            prodCurrentPriceUnit = prodCurrentPriceUnit.divide(decimal, 2, BigDecimal.ROUND_HALF_UP);
                            if (tempMoney.compareTo(prodCurrentPriceUnit) <= 0) {
                                BigDecimal subRateMoney = prodPrice.multiply(BigDecimal.valueOf(skuInfo.getNum())).multiply(taxReq.getLargeTax());
                                subRateMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                                tempRateMoney = tempRateMoney.add(subRateMoney).setScale(2, BigDecimal.ROUND_HALF_UP);

                            } else {
                                BigDecimal subRateMoney = prodPrice.multiply(BigDecimal.valueOf(skuInfo.getNum())).multiply(chargesNumber);
                                subRateMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                                tempRateMoney = tempRateMoney.add(subRateMoney).setScale(2, BigDecimal.ROUND_HALF_UP);
                            }
                        } else {
                            BigDecimal multiply = prodPrice.multiply(BigDecimal.valueOf(skuInfo.getNum())).multiply(chargesNumber);
                            multiply.setScale(2, BigDecimal.ROUND_HALF_UP);
                            tempRateMoney = tempRateMoney.add(multiply).setScale(2, BigDecimal.ROUND_HALF_UP);
                        }
                    }
                }
            }
            logger.info("计算税率是:{}", tempRateMoney);
            return tempRateMoney;
        } else {
            return BigDecimal.ZERO;
        }
    }

    @Override
    public void hiddenUserProdSearchHistory(String[] items, String userId) {
        if (items != null && items.length > 0) {
            if (items.length == 1) {
                prodSearchMapper.hiddenSearchUser(items[0], userId, new Date());
            } else {
                List<String> list = Arrays.asList(items);
                prodSearchMapper.batchBanSearchUser(userId, new Date(), list);
            }
        } else {
            prodSearchMapper.batchHiddenSearchUser(userId, new Date());
        }
    }

    @Override
    public ProdSearchArrayInfo findUserProdSearchArrayInfo(String userId) {
        ProdSearchArrayInfo info = new ProdSearchArrayInfo();
        info.setHistory(Collections.emptyList());
        if (userId != null && !"".equals(userId)) {
            List<ProdSearchHistoryInfo> history = prodSearchMapper.selectSearchHistoryInfo(userId);
            info.setHistory(history);
        }
        List<ProdSearchHistoryInfo> hotInfo = prodSearchMapper.selectSearchHotInfo();
        info.setHot(hotInfo);
        return info;
    }

    /**
     * @param prodName 1  所有
     *                 11 销量上
     *                 12 销量下
     *                 21 价格上
     *                 22 价格下
     *                 31 新品上(创建时间)
     *                 32 新品下(创建时间)
     * @param sorts
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<ProdOutInfo> findProdBySearch(String prodName, Integer sorts, String userId, Integer pageNum, Integer pageSize) throws Exception {
        String rankId = getRankId(userId);
        RankTab rankTab = rankTabMapper.selectByPrimaryKey(rankId);
        Integer rankNumber = rankTab.getRankNumber();
        String trimProd = prodName.trim();
        List<String> wordList = new ArrayList<>();
        String tempSpellWords = null;
        // 有分词没
        boolean has = false;
        String spellId = "";
        List<ProdSearchSpell> words = prodSearchMapper.findExactWords(trimProd);
        if (words != null && words.size() > 0) {
            ProdSearchSpell spell = words.get(0);
            String spellWords = spell.getSpellWords();
            String[] allWords = spellWords.split(",");
            wordList = Arrays.asList(allWords);
            tempSpellWords = spellWords;
            has = true;
            spellId = spell.getId();
        } else {
            Result parse = ToAnalysis.parse(trimProd);
            StopRecognition filter = new StopRecognition();
            filter.insertStopNatures("wkz");
            filter.insertStopNatures("wky");
            filter.insertStopNatures("wyz");
            filter.insertStopNatures("wyy");
            filter.insertStopNatures("wj");
            filter.insertStopNatures("ww");
            filter.insertStopNatures("wt");
            filter.insertStopNatures("wd");
            filter.insertStopNatures("wf");
            filter.insertStopNatures("wn");
            filter.insertStopNatures("wm");
            filter.insertStopNatures("ws");
            filter.insertStopNatures("wp");
            filter.insertStopNatures("wb");
            filter.insertStopNatures("wh");

//            filter.insertStopWords("我", "你", "的", "着", "了", "吧");
            parse.recognition(filter);

            StringBuilder spellWords = new StringBuilder();
            List<Term> terms = parse.getTerms();
            int size = terms.size();
            String[] allWords = new String[size];
            if (size > 0) {
                for (int i = 0; i < terms.size(); i++) {
                    spellWords.append(terms.get(i).getName());
                    allWords[i] = terms.get(i).getName();
                    if (i != size - 1) {
                        spellWords.append(",");
                    }
                }
            }
            wordList = Arrays.asList(allWords);
            tempSpellWords = spellWords.toString();
        }

        Date date = new Date();
        // 有分词,
        if (has) {
            List<ProdSearchUser> prodSearchUsers = prodSearchMapper.selectProdNameSearchSpell(spellId, userId);
            if (prodSearchUsers != null && prodSearchUsers.size() > 0) {
                String id = prodSearchUsers.get(0).getId();
                prodSearchMapper.updateProdNameSearch(id, date);
                prodSearchMapper.updateSearchUserOne(userId, spellId, date);
                prodSearchMapper.updateSearchHotOne(spellId, date);
            } else {
                ProdSearchUser psu = new ProdSearchUser();
                psu.setId(UUIDGenerator.generate()).setCreateTime(date)
                        .setUpdateTime(date)
                        .setDeleted(DeletedEnum.Exists_OK.getCode())
                        .setUserId(userId)
                        .setProdName(trimProd)
                        .setSpellId(spellId);
                ProdSearchHot prodSearchHot = prodSearchMapper.selectProdSearchHot(spellId);
                if (prodSearchHot == null) {
                    ProdSearchHot hot = new ProdSearchHot();
                    hot.setId(UUIDGenerator.generate())
                            .setCreateTime(date).setUpdateTime(date)
                            .setDeleted(DeletedEnum.Exists_OK.getCode())
                            .setModifyTimes(1)
                            .setProdName(trimProd)
                            .setSpellId(spellId);
                    prodSearchMapper.insertSearchHot(hot);
                } else {
                    prodSearchMapper.updateSearchHotOne(spellId, date);
                }
                prodSearchMapper.insertSearchUser(psu);
            }
        } else {
            ProdSearchSpell spell = new ProdSearchSpell();
            spellId = UUIDGenerator.generate();
            spell.setId(spellId)
                    .setCreateTime(date).setUpdateTime(date)
                    .setDeleted(DeletedEnum.Exists_OK.getCode())
                    .setProdName(trimProd)
                    .setSpellWords(tempSpellWords);

            prodSearchMapper.insertSearchSpell(spell);
            ProdSearchUser psu = new ProdSearchUser();
            psu.setId(UUIDGenerator.generate()).setCreateTime(date)
                    .setUpdateTime(date)
                    .setDeleted(DeletedEnum.Exists_OK.getCode())
                    .setUserId(userId)
                    .setProdName(trimProd)
                    .setSpellId(spellId);

            ProdSearchHot prodSearchHot = prodSearchMapper.selectProdSearchHot(spellId);
            if (prodSearchHot == null) {
                ProdSearchHot hot = new ProdSearchHot();
                hot.setId(UUIDGenerator.generate())
                        .setCreateTime(date).setUpdateTime(date)
                        .setDeleted(DeletedEnum.Exists_OK.getCode())
                        .setModifyTimes(1)
                        .setProdName(trimProd)
                        .setSpellId(spellId);
                prodSearchMapper.insertSearchHot(hot);
            } else {
                prodSearchMapper.updateSearchHotOne(spellId, date);
            }
            prodSearchMapper.insertSearchUser(psu);
        }
//        List<ProdSearchUser> prodSearchUsers = prodSearchMapper.selectProdNameSearch(trimProd, userId);
//        if (prodSearchUsers != null && prodSearchUsers.size() > 0) {
//            String id = prodSearchUsers.get(0).getId();
//            String spellId = prodSearchUsers.get(0).getSpellId();
//            prodSearchMapper.updateProdNameSearch(id, date);
//
//            prodSearchMapper.updateSearchUserOne(userId, spellId, date);
//            prodSearchMapper.updateSearchHotOne(spellId, date);
//        } else {
//
//            if (!has) {
//
//            } else {
//                spellId = words.get(0).getId();
//            }
//
//
//        }

        if (sorts == 11 || sorts == 12 || sorts == 31 || sorts == 32) {
            PageHelper.startPage(pageNum, pageSize, true);
        }
        Page<ProdOutInfo> result = prodSearchMapper.findSpellProd(wordList, sorts);
        if (sorts == 11 || sorts == 12) {
            result = prodSearchMapper.findSpellProdSells(wordList, sorts);
        }

        if (sorts == 31 || sorts == 32) {
            result = prodSearchMapper.findSpellProdTime(wordList, sorts);
        }


        List<ProdOutInfo> end = result.getResult();
        if (end == null || end.size() == 0) {
            return Collections.emptyList();
        } else {
            List<ProdCateOutInfo> infos = productMapper.selectCateByRankId(rankId);
            if (infos != null && infos.size() > 0) {
                List<Integer> collect = infos.stream().map(lt -> lt.getCateId()).collect(Collectors.toList());
                ArrayList<ProdOutInfo> tempEnd = new ArrayList<>();
                for (ProdOutInfo prod : result) {
                    String cateId = prod.getCateId();
                    if (collect.contains(Integer.valueOf(cateId))) {
                        tempEnd.add(prod);
                    }
                }
                end = tempEnd;
            }
            List<String> prodIds = end.stream().map(qq -> qq.getProdId()).distinct().collect(Collectors.toList());
            if (prodIds != null && prodIds.size() == 0) {
                return Collections.emptyList();
            }
            List<ProdCatePriceDso> priceDsos = productMapper.selectProdGroupPriceList(prodIds);


            // 所有的商品打折活动,包括所有的商品
            List<ProdJoinDiscount> discounts = productMapper.selectAllProductJoinDiscount();

            boolean specific = false;
            List<String> specUsers = customerMapper.findSpecificUser();
            if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {
                if (specUsers.contains(userId)) {
                    specific = true;
                }
            }
            if (!CollectionUtils.isEmpty(priceDsos)) {
                Map<String, List<ProdCatePriceDso>> map = priceDsos.stream().collect(Collectors.groupingBy(ProdCatePriceDso::getProductId));


                if (specific) {
                    for (ProdOutInfo prod : end) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                        if (prodCatePriceDsos != null) {
                            ProdCatePriceDso pcds = prodCatePriceDsos.get(0);
                            BigDecimal miniCost = pcds.getMiniCost();
                            miniCost = miniCost.multiply(BigDecimal.valueOf(pcds.getProdNum()));
                            prod.setProdPrice(miniCost);
                            prod.setCurrentPrice(miniCost);
                            prod.setBeauty(miniCost);
                            if (pcds.getBehalf() != null && pcds.getBehalf() == 0) {
                                prod.setHas(true);
                            } else {
                                prod.setHas(pcds.getNomNumbers() > 0);
                            }
                        } else {
                            prod.setProdPrice(BigDecimal.ONE);
                            prod.setCurrentPrice(BigDecimal.ONE);
                            prod.setBeauty(BigDecimal.ONE);
                        }
                    }
                } else {
                    for (ProdOutInfo prod : end) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                        if (prodCatePriceDsos != null) {
                            ProdCatePriceDso pcds = prodCatePriceDsos.get(0);
                            BigDecimal miniPrice = pcds.getMiniPrice();
                            if (pcds.getBehalf() != null && pcds.getBehalf() == 0) {
                                prod.setHas(true);
                            } else {
                                prod.setHas(pcds.getNomNumbers() > 0);
                            }
//                            prod.setHas(pcds.getNomNumbers() > 0);
                            prod.setProdPrice(miniPrice);
                            prod.setCurrentPrice(miniPrice);
                            prod.setBeauty(miniPrice);
                        } else {
                            BigDecimal price = productMapper.selectProdGroupPrice(prod.getProdId());
                            if (price != null) {
                                prod.setProdPrice(price);
                                prod.setCurrentPrice(price);
                                prod.setBeauty(price);
                            } else {
                                prod.setProdPrice(BigDecimal.ONE);
                                prod.setCurrentPrice(BigDecimal.ONE);
                                prod.setBeauty(BigDecimal.ONE);
                            }
                        }
                    }
                    end = switchToFastProd(end, userId, discounts);
                    // 直升商品
                    if (rankNumber > 0) {
                        for (ProdOutInfo info : end) {
                            if (info.getRankNum() < rankNumber && !info.isOneValue()) {
                                info.setRankIcon(rankTab.getRankIcon());
                                if (info.getKinds() == 2) {
                                    info.setRankPrice(info.getProdPrice().multiply(rankTab.getBigRankRate()));
                                } else {
                                    info.setRankPrice(info.getCurrentPrice().multiply(rankTab.getBigRankRate()));
                                }
                            }
                        }
                    }
                }
            }

            if (sorts == 21) {
                end.sort(Comparator.comparing(ProdOutInfo::getCurrentPrice).reversed());
            }
            if (sorts == 22) {
                end.sort(Comparator.comparing(ProdOutInfo::getCurrentPrice));
            }

            return end;
        }
    }

    @Override
    public ProductActivityInfo findProductActivityInfo(String userId) {
        List<TemporaryPic> tempPics = productMapper.selectTemporaryPic();
        if (null != tempPics && tempPics.size() > 0) {
            ProductActivityInfo productActivity = new ProductActivityInfo();
            TemporaryPic temp = tempPics.get(0);
            String imgUrl = temp.getActivityPic();
            String size = imgUrl.substring(imgUrl.lastIndexOf("_") + 1, imgUrl.lastIndexOf("."));
            String array[] = size.split("×");
            productActivity.setWidth(Integer.parseInt(array[0]));
            productActivity.setHeight(Integer.parseInt(array[1]));
            productActivity.setBgImgUrl(temp.getActivityPic());
            productActivity.setIsLink(temp.getIsPick());
            productActivity.setLinkType(temp.getUrlCategory());
            productActivity.setLink(temp.getActivityUrl());
            productActivity.setTitle(temp.getTitle());
            //活动
            if (temp.getCategory() == 0) {
                List<ProductActivityGoods> goods = productMapper.selectProductSaleActivityGoods();
                productActivity.setGoods(goods);
            } else if (temp.getCategory() == 1 || temp.getCategory() == 2) {
                List<ProductActivityGoods> goods = new ArrayList<>();
                List<ProductActivityGoods> saleActivityGoods = productMapper.selectProductSaleActivityGoods();
                if (saleActivityGoods.size() > 0) {
                    for (ProductActivityGoods good : saleActivityGoods) {
                        String prodAbbrName = good.getProdAbbrName();
                        if (prodAbbrName == null || "".equals(prodAbbrName)) {
                            good.setProdAbbrName(good.getProdName());
                        }
                    }
                    goods.addAll(saleActivityGoods);
                }
                List<ProductActivityGoods> activityGoods = productMapper.selectProductActivityGoods();
                if (activityGoods.size() > 0) {
                    for (ProductActivityGoods good : saleActivityGoods) {
                        String prodAbbrName = good.getProdAbbrName();
                        if (prodAbbrName == null || "".equals(prodAbbrName)) {
                            good.setProdAbbrName(good.getProdName());
                        }
                    }
                    goods.addAll(activityGoods);
                }
                productActivity.setGoods(goods);
            }

            return productActivity;
        }
        return null;
    }

    @Override
    public GreatBrandMain findActivityMainInfo(String userId) throws Exception {
        GreatBrandMain brandMain = new GreatBrandMain();
        List<String> prodIds = productMapper.selectAllTempProdIds();
        List<String> pics = productMapper.selectAllTempPicIds();
        brandMain.setCarouselsImg(pics);

        Page<ProdOutInfo> outInfos = productMapper.selectProdByCateIdPager4();
        List<ProdOutInfo> end = outInfos.getResult();
        UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
        int rankNum = userRankInfo.getRankNo();
        List<ProdCatePriceDso> priceDsos = productMapper.selectProdGroupPriceList(prodIds);


        // 所有的商品打折活动,包括所有的商品
        List<ProdJoinDiscount> discounts = productMapper.selectAllProductJoinDiscount();

        boolean specific = false;
        List<String> specUsers = customerMapper.findSpecificUser();
        if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {
            if (specUsers.contains(userId)) {
                specific = true;
            }
        }
        if (!CollectionUtils.isEmpty(priceDsos)) {
            Map<String, List<ProdCatePriceDso>> map = priceDsos.stream().collect(Collectors.groupingBy(ProdCatePriceDso::getProductId));


            if (specific) {
                for (ProdOutInfo prod : end) {
                    List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                    if (prodCatePriceDsos != null) {
                        ProdCatePriceDso pcds = prodCatePriceDsos.get(0);
                        BigDecimal miniCost = pcds.getMiniCost();
                        miniCost = miniCost.multiply(BigDecimal.valueOf(pcds.getProdNum()));
//                                BigDecimal miniCost = prodCatePriceDsos.get(0).getMiniCost();
                        prod.setProdPrice(miniCost);
                        prod.setBeauty(miniCost);
                        prod.setCurrentPrice(miniCost);
                        Integer behalf = pcds.getBehalf();
                        if (behalf != null) {
                            if (behalf == 0) {
                                prod.setHas(true);
                            } else {
                                prod.setHas(pcds.getNomNumbers() > 0);
                            }
                        } else {
                            prod.setHas(pcds.getNomNumbers() > 0);
                        }
                    } else {
                        prod.setCurrentPrice(BigDecimal.ONE);
                        prod.setProdPrice(BigDecimal.ONE);
                        prod.setBeauty(BigDecimal.ONE);
                    }
                }
                brandMain.setProdList(end);
            } else {
                for (ProdOutInfo prod : end) {
                    List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                    if (prodCatePriceDsos != null) {
                        ProdCatePriceDso pcds = prodCatePriceDsos.get(0);
                        BigDecimal miniPrice = pcds.getMiniPrice();

                        Integer behalf = pcds.getBehalf();
                        if (behalf != null) {
                            if (behalf == 0) {
                                prod.setHas(true);
                            } else {
                                prod.setHas(pcds.getNomNumbers() > 0);
                            }
                        } else {
                            prod.setHas(pcds.getNomNumbers() > 0);
                        }
                        prod.setCurrentPrice(miniPrice);
                        prod.setProdPrice(miniPrice);
                        prod.setBeauty(miniPrice);
                    } else {
                        BigDecimal price = productMapper.selectProdGroupPrice(prod.getProdId());
                        if (price == null) {
                            prod.setCurrentPrice(BigDecimal.ONE);
                            prod.setProdPrice(BigDecimal.ONE);
                            prod.setBeauty(BigDecimal.ONE);
                        } else {
                            prod.setCurrentPrice(price);
                            prod.setBeauty(price);
                            prod.setProdPrice(price);
                        }
                    }
                }
                end = switchToFastProd(end, userId, discounts);
                // 直升商品
                if (rankNum > 0) {
                    for (ProdOutInfo prodOutInfo : end) {

                        if (!prodOutInfo.isOneValue() && prodOutInfo.getRankNum() < rankNum) {
                            prodOutInfo.setRankIcon(userRankInfo.getPriceIcon());
                            // 直升商品
                            if (prodOutInfo.getKinds() == 2) {
                                prodOutInfo.setRankPrice(prodOutInfo.getProdPrice().multiply(userRankInfo.getBigRankRate()));
                            } else {
                                prodOutInfo.setRankPrice(prodOutInfo.getCurrentPrice().multiply(userRankInfo.getBigRankRate()));
                            }
                        }
                    }
                }
                brandMain.setProdList(end);
            }
        }
        return brandMain;
    }

    @Override
    public List<String> findCateImgs(String cateId) {
        if (cateId != null && !"".equals(cateId) && !"undefined".equals(cateId)) {
            List<String> list = customerMapper.selectCateImgs(cateId);
            return list;
        } else {
            return null;
        }
    }


    public boolean checkSuper(String userId) {
        List<String> specUsers = customerMapper.findSpecificUser();
        if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {
            if (specUsers.contains(userId)) {
                return true;
            }
        }
        return false;
    }

    public List<ProdTransInfo> findProdTransInfo(String tradeNum) {
        List<ProdTransInfo> prodTransRoadInfo = prodBaseMapper.findProdTransRoadInfo(tradeNum);
        return prodTransRoadInfo;
    }

    public List<ProdTransInfo> findProdTransInfo2(Integer tradeType) {
        List<ProdTransInfo> prodTransRoadInfo = prodBaseMapper.findProdTransRoadInfo2(tradeType);
        return prodTransRoadInfo;
    }
}
